<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/4/22
 * Time: 15:38
 */

namespace app\admin\controller;
use app\common\controller\Backend;

use think\Loader;
use think\Db;
use fast\Pinyin;
class Test extends Backend
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = '';
    protected $car = [];
    protected $db = null;
    //protected $payload='';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $cars = Db::name('car')->field('IMEI,pinyin,circuit_id')->where("IMEI!=''")->select();

        if($cars)
        {
            foreach ($cars as $k=>$v)
            {
                $this->car[$v['IMEI']]['pinyin'] = $v['pinyin'];
                $this->car[$v['IMEI']]['circuit'] = $v['circuit_id'];
            }
        }
        $dbc = array(
            'hostname' => '127.0.0.1',
            'username' => 'root',
            'password' => 'root',
            'database' => 'school'
        );

        $mysqlnd = function_exists('mysqli_fetch_all');

        if ($mysqlnd) {
            $database = $dbc['database'];
            $db_hostname = $dbc['hostname'];
            $db_username = $dbc['username'];
            $db_password = $dbc['password'];
            $dsn = "mysql:dbname=$database;host=$db_hostname";
            $db = new \PDO($dsn, $db_username, $db_password);
            $db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, 0);
            $this->db=$db;
        }
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }


    public function connect($client_id)
    {
        $server = 'develop.rltest.cn';     // change if necessary
        $port = 1883;                     // change if necessary

        $client_id = $client_id; // make sure this is unique for connecting to sever - you could use uniqid()
        Loader::import('phpmqtt/phpMQTT', EXTEND_PATH);

        $mqtt = new \phpmqtt\phpMQTT($server, $port, $client_id);

        $mqtt->debug = true;
        return $mqtt;
    }

    //获取主动位置
    public function sub()
    {

        $client_id = time().rand();
        $mqtt = $this->connect($client_id);
        $username = 'rl517';                   // set your username
        $password = 'rlian2022';                   // set your password
        if(!$mqtt->connect(true, NULL, $username, $password)) {
            echo '链接失败';exit;
        }

        $topics_name = "ScBusTem/DevRegularInfo";
        //$topics['ScBusTem/DevRegularInfo'] = array('qos' => 0, 'function' => 'procMsg');
        $topics[$topics_name] = array("qos" => 0, "function" =>array($this,"onMessage"));
        $mqtt->subscribe($topics, 0);

        //$nowtime=time();
        while($mqtt->proc()) {
            /*global $payload;
            if(empty($payload)){

                echo $payload;  //订阅到的消息
                continue;
            }*/
           /* if($nowtime==(time()-2)){
                break;
            }*/
        }

        $mqtt->close();
    }

    /**
     * 在此处接MQtt的信息 进行业务处理
     * @param $topic
     * @param $msg
     */
    function onMessage($topic,$msg){
        //echo 'Msg Recieved: ' . date('r') . "\n";
       // echo "Topic: {$topic}\n\n";
        echo $msg."\n\n";
        if($msg)
        {
            $msgs = json_decode($msg,true);
            if(isset($this->car[$msgs['IMEI']]))
            {
                $msgs['DTIME'] = date('Y-m-d',$msgs['TIME']);
                $tableName = 'fa_car_'.Pinyin::get($this->car[$msgs['IMEI']]['pinyin']);
                $sql = "INSERT INTO {$tableName} (IMEI,CSQ,GPS_LNG,GPS_LAT,SPEED,SYS_VER,TEMP,HUM,INIT,TIME,DTIME) VALUES ('{$msgs['IMEI']}','{$msgs['CSQ']}','{$msgs['GPS_LNG']}','{$msgs['GPS_LAT']}','{$msgs['SPEED']}','{$msgs['SYS_VER']}','{$msgs['TEMP']}','{$msgs['HUM']}','{$msgs['INIT']}','{$msgs['TIME']}','{$msgs['DTIME']}')";
                $this->db->exec($sql);

            }
        }


    }
    //获取学生上下车打开位置时间
    public function info()
    {
        $client_id = time().rand();

        $mqtt = $this->connect($client_id);
        $username = 'rl517';                   // set your username
        $password = 'rlian2022';                   // set your password
        if(!$mqtt->connect(true, NULL, $username, $password)) {
            echo '链接失败';exit;
        }
        $topics_name = "ScBusTem/RCInfoMsg";
        //$topics['ScBusTem/DevRegularInfo'] = array('qos' => 0, 'function' => 'procMsg');
        $topics[$topics_name] = array("qos" => 0, "function" =>array($this,"onMessageInfo"));
        $mqtt->subscribe($topics, 0);


        while($mqtt->proc()) {

        }

        $mqtt->close();

    }

    function onMessageInfo($topic,$msg){
        //echo 'Msg Recieved: ' . date('r') . "\n";
        // echo "Topic: {$topic}\n\n";
        echo $msg."\n\n";
        if($msg)
        {
            $msgs = json_decode($msg,true);
            $msgs['DTIME'] = date('Y-m-d',$msgs['TIME']);
            $circuit_id = $this->car[$msgs['IMEI']]['circuit'];
            $tableName = 'fa_on_off_car';
            $sql = "INSERT INTO {$tableName} (IMEI,TIME,RC_TYPE,GPS_LNG,MSGID,RC_NUM,RC_TOTAL,GPS_LAT,RC_PRES,DTIME,circuit_id) VALUES ('{$msgs['IMEI']}','{$msgs['TIME']}','{$msgs['RC_TYPE']}','{$msgs['GPS_LNG']}','{$msgs['MSGID']}','{$msgs['RC_NUM']}','{$msgs['RC_TOTAL']}','{$msgs['GPS_LAT']}','{$msgs['RC_PRES']}','{$msgs['DTIME']}','{$circuit_id}')";
            $this->db->exec($sql);
        }


    }
    //设置设备配置（下发刷卡配置）
    public function setRcDevConfig()
    {

        $client_id = time().rand();
        $topics_name = "ScBusTem/SetRCDevConfig/861714055270312";
        $mqtt = $this->connect($client_id);
        $username = 'rl517';                   // set your username
        $password = 'rlian2022';                   // set your password

        $data = [];
        //$data['IMEI'] = '861714055270312';//状态：1是上车，2是下车
        $data['RC_Type'] = 1;//状态：1是上车，2是下车
        $data['RC_Pres'] = 0;//车上剩余人数 上车时0
        $data['RC_Total'] = 10;//总人数
        //$data['TIME'] = time();//时间戳

        if ($mqtt->connect(true, NULL, $username, $password)) {
            $mqtt->publish($topics_name, json_encode($data), 0, false);
            $mqtt->close();
            $this->success('配置成功');
        } else {
            $this->success('配置成功');
        }
    }

}